﻿#region Licence
// <copyright file="Core/LocalizedService.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>11/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Markup;
using Database.POCO;
using GalaSoft.MvvmLight.Ioc;
using Helpers.Mef;
using Interfaces;

#endregion

namespace Core.Services
{
    public class LocalizedService : IServiceLocalize, IPartImportsSatisfiedNotification
    {
        public IServiceDatabase DatabaseService
        {
            get { return SimpleIoc.Default.GetInstance<IServiceDatabase>(); }
        }

        [ImportMany(typeof(ResourceDictionary))]
        public IEnumerable<Lazy<ResourceDictionary, IDictionary<string, object>>> LangDictionaries { get; set; } 

        public Dictionary<string, string> LabelsDictionary = new Dictionary<string, string>(); 
        private string _culture;

        public LocalizedService()
        {
            _culture = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
            var actualCulture = new CultureInfo(_culture);
            Thread.CurrentThread.CurrentCulture = actualCulture;
            Thread.CurrentThread.CurrentUICulture = actualCulture;

            //Indispensable pour effectuer le changement sur les élements d'affichage
            FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement),new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

            CompositionInitializer.AddPartAndComposeContainer(this);
        }

        public string LocalizedFromKey(string key, bool isUpperCase = false)
        {
            if (LabelsDictionary.ContainsKey(key))
            {
                string label;
                if (LabelsDictionary.TryGetValue(key, out label))
                {
                    return isUpperCase ? ReplaceSymbolByCarriageReturn(label).ToUpper() : ReplaceSymbolByCarriageReturn(label);
                }
            }
            return key;
        }

        public string LocalizedColumnTable(string table, string column, bool isUpperCase = false)
        {
            var key = string.Format("{0}.{1}", table, column);
            return LocalizedFromKey(key, isUpperCase);
        }

        public void SetCulture(string culture)
        {
            _culture = culture;
            var actualCulture = new CultureInfo(_culture);
            Thread.CurrentThread.CurrentCulture = actualCulture;
            Thread.CurrentThread.CurrentUICulture = actualCulture;

            //Indispensable pour effectuer le changement sur les élements d'affichage
            FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

            LoadLabelsFromCulture();
        }

        public bool InitialLocalizedValues()
        {
            try
            {
                InitialSysLabels();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool LoadLocalizedValues()
        {
            try
            {
                LoadLabelsFromCulture();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void OnImportsSatisfied()
        {
            if (!string.IsNullOrEmpty(_culture))
            {
                LoadLabelsFromCulture();
            }
        }

        #region protected

        protected string ReplaceSymbolByCarriageReturn(string label)
        {
            return label.Replace(@"\$", Environment.NewLine);
        }

        protected void LoadLabelsFromCulture()
        {
            LabelsDictionary.Clear();
            var labels = DatabaseService.Service.Where<SysLabels>(l => l.Culture == _culture);
            foreach (var label in labels)
            {
                LabelsDictionary.Add(label.Cle, label.Label);
            }
        }

        protected void InitialSysLabels()
        {
            if (LangDictionaries != null && LangDictionaries.Any())
            {
                foreach (var dictionary in LangDictionaries)
                {
                    var dict = dictionary.Value;
                    foreach (var key in dict.Keys)
                    {
                        var label = new SysLabels
                                    {
                                        Cle = key.ToString(),
                                        Label = dict[key].ToString(),
                                        Culture = dictionary.Metadata["Culture"].ToString()
                                    };

                        var labels = DatabaseService.Service.Where<SysLabels>(l => l.Cle == label.Cle && l.Culture == label.Culture);
                        if (labels.Any())
                        {
                            var labelOld = labels.First();
                            DatabaseService.Service.Delete<SysLabels>(labelOld);
                        }
                        DatabaseService.Service.Add<SysLabels>(label);
                    }
                    DatabaseService.Service.SaveChanges<SysLabels>();
                }
            }
        }

        #endregion
    }
}
